using System.Collections.Generic;
using System.Windows.Forms;
using HgAdapter;
using HogoLogic.HgFileSystem;

namespace FileSystemView
{
	partial class HogoFileView : UserControl
	{
		readonly HogoFileListItemVisualizer visualizer = new HogoFileListItemVisualizer();
		private HgDirectoryInfo currentDirectory;
		
		public HogoFileView()
		{
			InitializeComponent();
		}
		
		public void Open(HgDirectoryInfo directoryInfo)
		{
			currentDirectory = directoryInfo;
			Reload();
		}

		private List<string> GetSelectedFilesWithStatuses(params VersionStatus[] statuses)
		{
			List<string> result = new List<string>();
			foreach (ListViewItem listViewItem in innerListView.SelectedItems)
			{
				HgFileInfo curFile = visualizer.GetFileForListViewItem(listViewItem);
				foreach (VersionStatus status in statuses)
				{
					if (curFile.VersionStatus == status)
						result.Add(curFile.FullName.Substring(ProjectCommitInfo.Instance.ProjectPath.Length + 1));
				}
			}
			return result;			
		}

		private void commitItem_Click(object sender, System.EventArgs e)
		{
			Commit();
		}

		private void addItem_Click(object sender, System.EventArgs e)
		{
			Add();
		}

		private void Reload()
		{
			innerListView.Items.Clear();
			innerListView.Items.AddRange(visualizer.MakeListViewItemArray(currentDirectory));
		}

		private void Commit()
		{
			if (commitDialog.ShowDialog() == DialogResult.OK)
			{
				List<string> filesToCommit = GetSelectedFilesWithStatuses(VersionStatus.Changed, VersionStatus.Added);
				(new HgCommit()).Run(filesToCommit, commitDialog.CommitMessage);

				ProjectCommitInfo.Instance.Reload();
				Reload();
			}
		}

		private void Add()
		{
			List<string> filesToAdd = GetSelectedFilesWithStatuses(VersionStatus.Unversioned);
			(new HgAdd()).Run(filesToAdd);

			ProjectCommitInfo.Instance.Reload();
			Reload();
		}
	}
}
